package com.hfzy.ihk.web.websocket.support.toBrowser;

import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.web.websocket.support.base.CommonWebSocketHandshakeInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/20.
 *
 * @author wws
 */
public class PluginWebSocketHandshakeInterceptor extends CommonWebSocketHandshakeInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(PluginWebSocketHandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        /**连接安全验证*/
        boolean validateSource = super.beforeHandshake(request,response,wsHandler,attributes);

        if(!validateSource)
            return false;
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        String userId = servletRequest.getParameter("userId");
        String token  = servletRequest.getParameter("token");

        logger.debug("plugin beforeHandshake ----》userId:{},token:{}",userId,token);

        if(StringUtil.isEmpty(userId) || StringUtil.isEmpty(token) || !StringUtil.isNumeric(userId))
            return false;

        attributes.put("userId",userId);
        attributes.put("token",token);

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        logger.debug("websocket after Handshake!");
    }

}
